<!-- src/views/admin/DishForm.vue -->
<template>
  <div>
    <h2>{{ isEdit ? '编辑菜品' : '添加菜品' }}</h2>
    <form @submit.prevent="onSubmit">
      <input v-model="form.name" placeholder="菜名" required />
      <input v-model.number="form.price" placeholder="价格" required type="number" />
      <select v-model.number="form.category">
        <option v-for="c in categories" :value="c.categoryId">{{ c.categoryName }}</option>
      </select>
      <input v-model.number="form.stock" placeholder="库存" required type="number" />
      <input v-model="form.imageUrl" placeholder="图片地址" />
      <textarea v-model="form.description" placeholder="描述"></textarea>
      <button type="submit">{{ isEdit ? '更新' : '添加' }}</button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import service from '@/utils/request.js'

const route = useRoute()
const router = useRouter()
const isEdit = route.path.includes('edit')
const form = ref({
  name: '',
  price: 0,
  category: 1,
  stock: 0,
  imageUrl: '',
  description: ''
})
const categories = ref([])

async function fetchCategories() {
  const res = await service.get('/menu/categories')
  categories.value = res.data.data.categories || []
}

async function fetchDishDetail() {
  const id = route.params.id
  const res = await service.get(`/menu/dishes/${id}`)
  if (res.data.code === 0) {
    const d = res.data.data
    form.value = {
      name: d.dishName,
      price: d.price,
      category: d.categoryId,
      stock: d.stock || 0,
      imageUrl: d.imageUrl || '',
      description: d.description || ''
    }
  }
}

async function onSubmit() {
  if (isEdit) {
    await service.post(`/admin/dishes/${route.params.id}`, form.value)
    alert('更新成功')
  } else {
    await service.post('/admin/dishes', form.value)
    alert('添加成功')
  }
  router.push('/admin/dishes')
}

onMounted(() => {
  fetchCategories()
  if (isEdit) fetchDishDetail()
})
</script>
